<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-row :gutter="10">
        <el-form-item label="系统单号" prop="code">
          <el-input v-model="queryParams.code" placeholder="请输入系统单号" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="客户类型" prop="customerType">
          <el-select filterable v-model="queryParams.customerType" placeholder="请选择客户类型" clearable>
            <el-option v-for="dict in dict.type.CustomerType" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="结算方式" prop="feeType">
          <el-select filterable v-model="queryParams.feeType" placeholder="请选择结算方式" clearable>
            <el-option v-for="dict in dict.type.Clearing" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="交付方式" prop="handoverType">
          <el-select filterable v-model="queryParams.handoverType" placeholder="请选择交付方式" clearable>
            <el-option v-for="dict in dict.type.HandoverType" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
      </el-row>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="success" icon="el-icon-more" size="mini" @click="moreFilterQuery">更多查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-circle-check" size="mini" :disabled="single" @click="handleReceive"
          v-hasPermi="['order:order:edit']">接收回单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload" size="mini" :disabled="multiple" @click="handleUpload"
          v-hasPermi="['order:order:edit']">回单上传</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-position" size="mini" :disabled="single" @click="handleSubmit"
          v-hasPermi="['order:order:edit']">回单交单</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed/>
      <el-table-column width="100" label="组织机构" align="center" prop="name" />
      <el-table-column width="150" label="订单号" align="center" prop="code">
        <template #default="scope">
          <el-tooltip v-if="scope.row.isAbnormal == 1" content="查看异常信息" placement="top">
            <el-tag type="danger" effect="dark" @click="openAbnormal(scope.row)"> {{ scope.row.code }} </el-tag>
          </el-tooltip>
          <span v-else>{{ scope.row.code }}</span>
        </template>
      </el-table-column>
      <el-table-column width="140" label="发货单号" align="center" prop="relateBill1" />
      <el-table-column width="140" label="客户单号" align="center" prop="relateBill2" />
      <el-table-column label="开单日期" align="center" prop="time" width="100" />
      <el-table-column label="订单状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="dict.type.OrderStatus" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column width="100" label="回单" align="center" prop="isBack">
        <template #default="scope">
          <div v-if="scope.row.isBack === 1">
            <el-button v-if="scope.row.isBack === 1 && scope.row.isUpload === 1"
                       type="primary" size="mini"
                       @click="openBackImages(scope.row)"
            >份数:{{ scope.row.backNumber }},查看</el-button>
            <span v-else>份数:{{ scope.row.backNumber }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="客户类型" align="center" prop="customerType">
        <template #default="scope">
          <dict-tag :options="dict.type.CustomerType" :value="scope.row.customerType" />
        </template>
      </el-table-column>
      <el-table-column width="220" label="客户名称" align="left" prop="customerName" />
      <el-table-column width="80" label="是否拆单" align="center" prop="isTake">
        <template #default="scope">
          <dict-tag :options="dict.type.CommIsNot" :value="scope.row.isTake" />
        </template>
      </el-table-column>
      <el-table-column width="80" label="结算方式" align="center" prop="feeType">
        <template #default="scope">
          <dict-tag :options="dict.type.Clearing" :value="scope.row.feeType" />
        </template>
      </el-table-column>
      <el-table-column width="150" label="出发运点" align="center" prop="startZoneName" />
      <el-table-column width="100" label="目的站" align="center" prop="toOrganizationName" />
      <el-table-column width="200" label="目的运点" align="center" prop="endZoneName" />
      <el-table-column width="80" label="交付方式" align="center" prop="handoverType">
        <template #default="scope">
          <dict-tag :options="dict.type.HandoverType" :value="scope.row.handoverType" />
        </template>
      </el-table-column>
      <el-table-column width="140" label="货名" align="center" prop="productName" />
      <el-table-column width="80" label="总金额" align="center" prop="createName" />
      <el-table-column width="80" label="件数" align="center" prop="number" />
      <el-table-column width="80" label="体积" align="center" prop="volume" />
      <el-table-column width="80" label="重量" align="center" prop="weight" />
      <el-table-column width="80" label="计重" align="center" prop="jzWeight" />
      <el-table-column label="要求发运时间" align="center" prop="planLeaveTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.planLeaveTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="要求到达时间" align="center" prop="planArriveTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.planArriveTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际发运时间" align="center" prop="factLeaveTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.factLeaveTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际运抵日期" align="center" prop="factArriveTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.factArriveTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column width="80" label="运输方式" align="center" prop="shipmentMethod" >
        <template #default="scope">
          <dict-tag :options="dict.type.TransportMenth" :value="scope.row.shipmentMethod" />
        </template>
      </el-table-column>
      <el-table-column width="80" label="运输性质" align="center" prop="transportPro">
        <template #default="scope">
          <dict-tag :options="dict.type.TransportPro" :value="scope.row.transportPro" />
        </template>
      </el-table-column>
      <el-table-column width="140" label="在途跟踪" align="center" prop="createName">
        <template #default="scope">
          <el-button type="primary" size="mini" @click="openTrack(scope.row)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column width="80" label="是否超期" align="center" prop="customerIsExceed">
        <template #default="scope">
          <dict-tag :options="dict.type.CommIsNot" :value="scope.row.customerIsExceed" />
        </template>
      </el-table-column>
      <el-table-column width="120" label="入库区域" align="center" prop="zoneStorerName" />
      <el-table-column width="100" label="创建人" align="center" prop="createName" />
      <el-table-column width="160" label="创建时间" align="center" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column width="100" label="修改人" align="center" prop="modifyName" />
      <el-table-column width="160" label="修改时间" align="center" prop="modifyTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column width="140" label="备注" align="center" prop="description" />
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog :close-on-click-modal="false" :title="orderTrackTitle" :visible.sync="orderTrackVisible" width="550px"
      append-to-body>
      <div class="block" style="max-height: 600px; overflow-y: scroll;">
        <el-timeline>
          <el-timeline-item v-for="(item, index) in orderTrackList" :key="index" :timestamp="item.time" placement="top">
            <el-card>
              <h4>{{ item.event }}</h4>
              <p>{{ item.createName }} 提交于 {{ item.time }}</p>
              <div v-if="item.imgUrls">
                <el-image v-for="(img, ind) in item.imgUrls" :key="ind" style="width: 100px; height: 100px;margin: 10px 10px;" :src="img" :preview-src-list="item.imgUrls"/>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>
    <order-more-query ref="orderMoreQuery" :query-params="queryParams" @ok="handleQuery"></order-more-query>

    <!-- 上传图片-->
    <el-dialog :close-on-click-modal="false" title="回单图片上传" :visible.sync="backPicOpen" width="550px" append-to-body>
      <el-form ref="uploadForm" :model="uploadForm" :rules="uploadRules" label-width="80px">
        <el-form-item label="回单图片" prop="images">
          <image-upload v-model="uploadForm.images" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUploadForm">确 定</el-button>
        <el-button @click="cancelUpload">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看图片-->
    <el-dialog title="回单图片" :visible.sync="imageOpen" width="700px" append-to-body>
      <el-image v-for="(img, ind) in imageUrls" :key="ind" :src="img" :preview-src-list="imageUrls"
                style="width: 150px; height: 150px;margin-right: 10px;margin-bottom: 10px;border: #729aea solid 1px;" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="imageOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrder, receive, submit, uploadOrderBackImage  } from "@/api/order/orderBack";
import OrderTrack from "@/views/order/order/component/orderTrack.vue";
import OrderMoreQuery from "@/views/order/order/component/moreQuery.vue";
import { listOrderTrackByOrderId } from "@/api/order/orderTrack";


export default {
  name: "BackOrder",
  components: { OrderMoreQuery, OrderTrack },
  dicts: ['Clearing', 'CustomerType', 'OrderStatus', 'HandoverType', 'ConfirmStatus', 'TransportMenth', 'TransportPro', 'CommIsNot', 'DB_JC_ORG'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单管理表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      moreFilter: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        name: null,
        status: null,
        backNumber: null,
        customerIsExceed: null,
        customerName: null,
        customerType: null,
        feeType: null,
        fyTime: null,
        handoverType: null,
        isAbnormal: null,
        isBack: null,
        isUpload: null,
        isBilling: null,
        jsStatus: null,
        number: null,
        orderMileage: null,
        relateBill1: null,
        relateBill2: null,
        relateBill3: null,
        relateBill4: null,
        relateBill5: null,
        salePerson: null,
        shipmentMethod: null,
        isConfirm: null,
        time: null,
        transportPro: null,
        ydTime: null,
        jcCustomerId: null,
        jcOrganizationId: null,
        jcSettlementId: null,
        jcDispatchId: null,
        factArriveTime: null,
        factLeaveTime: null,
        planArriveTime: null,
        planLeaveTime: null,
        jcFromOrganizationId: null,
        jcToOrganizationId: null,
        hxMoney: null,
        hxType: null,
        whxMoney: null,
        jcZoneStoreroomId: null,
        jcEndZoneId: null,
        jcStartZoneId: null,
        isTake: null,
        agent: null,
        qsTime: null,
        qsPerson: null,
        jzWeight: null,
        jcPrescoId: null,
        jsType: null,
        price: null,
        zAmount: null,
        // 时间范围
        daterangeTime: [],
        // 时间范围
        daterangeFactArriveTime: [],
        // 时间范围
        daterangeFactLeaveTime: [],
        // 时间范围
        daterangePlanArriveTime: [],
        // 时间范围
        daterangePlanLeaveTime: [],
      },
      orderTrackVisible: false,
      orderTrackTitle: '订单追踪',
      orderTrackList: [],
      imageOpen: false,
      imageUrls: [],
      backPicOpen: false,
      uploadForm: {
        jcOrderBackId: null,
        images: null,
      },
      uploadRules: {
        images: [
          { required: true, message: '请上传图片', trigger: 'blur' }
        ]
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询订单管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.queryParams.daterangeTime && '' !== this.queryParams.daterangeTime) {
        this.queryParams.params["beginTime"] = this.queryParams.daterangeTime[0];
        this.queryParams.params["endTime"] = this.queryParams.daterangeTime[1];
      }
      if (null != this.queryParams.daterangeFactArriveTime && '' !== this.queryParams.daterangeFactArriveTime) {
        this.queryParams.params["beginFactArriveTime"] = this.queryParams.daterangeFactArriveTime[0];
        this.queryParams.params["endFactArriveTime"] = this.queryParams.daterangeFactArriveTime[1];
      }
      if (null != this.queryParams.daterangeFactLeaveTime && '' !== this.queryParams.daterangeFactLeaveTime) {
        this.queryParams.params["beginFactLeaveTime"] = this.queryParams.daterangeFactLeaveTime[0];
        this.queryParams.params["endFactLeaveTime"] = this.queryParams.daterangeFactLeaveTime[1];
      }
      if (null != this.queryParams.daterangePlanArriveTime && '' !== this.queryParams.daterangePlanArriveTime) {
        this.queryParams.params["beginPlanArriveTime"] = this.queryParams.daterangePlanArriveTime[0];
        this.queryParams.params["endPlanArriveTime"] = this.queryParams.daterangePlanArriveTime[1];
      }
      if (null != this.queryParams.daterangePlanLeaveTime && '' !== this.queryParams.daterangePlanLeaveTime) {
        this.queryParams.params["beginPlanLeaveTime"] = this.queryParams.daterangePlanLeaveTime[0];
        this.queryParams.params["endPlanLeaveTime"] = this.queryParams.daterangePlanLeaveTime[1];
      }
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    moreFilterQuery() {
      this.$refs.orderMoreQuery.moreFilterQuery();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.daterangeTime = [];
      this.queryParams.daterangeFactArriveTime = [];
      this.queryParams.daterangeFactLeaveTime = [];
      this.queryParams.daterangePlanArriveTime = [];
      this.queryParams.daterangePlanLeaveTime = [];
      this.resetForm("queryForm");
      this.$refs.orderMoreQuery.resetQuery();
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.backId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    openTrack(row) {
      this.orderTrackVisible = true
      this.orderTrackList = []
      /** 查询订单追踪列表 */
      this.loading = true;
      listOrderTrackByOrderId(row.jcOrderId).then(response => {
        this.loading = false;
        this.orderTrackList = response.data;
        // 处理图片地址
        if (this.orderTrackList.length > 0) {
          this.orderTrackList.forEach(item => {
            if (item.images) {
              // 每个图片地址都加上baseUrl
              item.imgUrls = item.images.split(',').map(d => process.env.VUE_APP_BASE_API + d)
            }
          })
        }
      })
    },
    handleReceive() {
      this.$confirm('是否确认接收回单？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        receive(this.ids).then(response => {
          this.$message({type: 'success', message: '接收回单成功!'});
          this.getList();
        });
      }).catch(() => {});
    },
    handleSubmit() {
      this.$confirm('是否确认回单交单？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        submit(this.ids).then(response => {
          this.$message({type: 'success', message: '回单交单成功!'});
          this.getList();
        }).catch(() => {});
      })
    },
    handleUpload() {
      this.backPicOpen = true;
    },
    submitUploadForm() {
      this.$refs.uploadForm.validate(valid => {
        if (valid) {
          this.uploadForm.jcOrderBackId = this.ids[0];
          uploadOrderBackImage(this.uploadForm).then(response => {
            this.$message({type: 'success', message: '回单上传成功!'});
            this.resetUploadForm();
            this.backPicOpen = false;
            this.getList();
          }).catch(() => {});
        }
      })
    },
    cancelUpload() {
      this.resetUploadForm();
      this.backPicOpen = false;
    },
    resetUploadForm() {
      this.uploadForm = {
        jcOrderBackId: null,
        images: null,
      };
      this.resetForm("uploadForm");
    },
    openBackImages(row) {
      this.imageUrls = []
      this.imageOpen = true;
      if (row.images) {
        this.imageUrls = row.images.map(d => {
          return process.env.VUE_APP_BASE_API + d.url
        });
      }
      console.log('imageUrls' + this.imageUrls)
      debugger
    },
  }
};
</script>
